/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ticketManager.search;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import ticketManager.model.Problem;
import ticketManager.model.ProblemStates;
/**
 *
 * @author Administrator
 */
@ManagedBean(name = "search")
@RequestScoped
public class ProblemsSearch {
    private String searchstring;
    public List<Problem> problemssearched;
    
    @PersistenceContext
    EntityManager em;
    public void doSearchProblems()
    {
        String s = searchstring;
        
        List<Problem> searchProblemsDescription = em.createQuery("select p from Problem p where p.description like :u").setParameter("u", "%" + s + "%")
                .getResultList();
        
       List<Problem> searchProblemsProduct = em.createQuery("select p from Problem p join p.productinvolve pro where p.productinvolve.title = :u").setParameter("u", s)
                .getResultList();
        
        List<Problem> searchProblemsCreator = em.createQuery("select p from Problem p join p.creator creator where p.creator.userName = :u").setParameter("u", s)
                .getResultList();
        
        List<Problem> searchProblemsAssigner = em.createQuery("select p from Problem p join p.assigner assigner where p.assigner.userName = :u").setParameter("u", s)
                .getResultList();
        
        problemssearched = new ArrayList();
        problemssearched.addAll(searchProblemsDescription);
        problemssearched.addAll(searchProblemsProduct);
        problemssearched.addAll(searchProblemsCreator);
        problemssearched.addAll(searchProblemsAssigner);
        
        Set<Problem> set = new HashSet<Problem>();  
        for (int i = 0; i < problemssearched.size(); i++) {  
            Problem p = problemssearched.get(i);  
            set.add(p);             
        }  
        
        problemssearched.clear();
        
        for (Iterator<Problem> it = set.iterator(); it.hasNext();){  
            problemssearched.add(it.next());  
        }  

        
    }
    public String getSearch() {
        return searchstring;
    }

    public void setSearch(String search) {
        this.searchstring = search;
    }
    
    public List<Problem> getProblemssearched() {
        return problemssearched;
    }
}
